package com.project.dao.impl;

import com.project.bean.ClassBean;
import com.project.dao.IClassDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ClassDaoImpl extends BaseDao implements IClassDao {
    @Override
    public List<ClassBean> findAll() {
        List<ClassBean> classList = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_class");
            rs = ps.executeQuery();
            while (rs.next()) {
                ClassBean classBean = new ClassBean();
                classBean.setId(rs.getInt("pk_classId"));
                classBean.setName(rs.getString("c_name"));
                classBean.setTeacher(rs.getString("c_teacher"));
                classBean.setTime(LocalDate.parse(rs.getString("c_time")));
                classList.add(classBean);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close();
        }


        return classList;
    }

    @Override
    public void del(int classId) {
        this.setConnection();
        try {
            ps = con.prepareStatement("delete from t_class where pk_classId=? ");
            ps.setObject(1, classId);
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            close();
        }
    }

    @Override
    public void add(ClassBean classBean) {
        this.setConnection();
        try {
            ps = con.prepareStatement("INSERT INTO t_class(c_name,c_teacher,c_time)values (?,?,?)");
            ps.setObject(1, classBean.getName());
            ps.setObject(2, classBean.getTeacher());
            ps.setObject(3, classBean.getTime());
            ps.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            close();
        }
    }
}
